package com.question.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.question.pojo.dto.AnswerStats;
import com.question.pojo.dto.MajorStatDTO;
import com.question.pojo.entity.UserAnswer;
import com.question.pojo.vo.UserAnswerVO;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

import java.util.List;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

@Mapper
public interface UserAnswerMapper extends BaseMapper<UserAnswer> {

    /**
     * 统计所有用户答题信息
     */
    @Select("select u.user_id, u.username, count(ua.user_id) as answerCount from user u " +
            "left join user_answers ua on u.user_id = ua.user_id " +
            //"where u.is_admin = 0 " +
            "group by u.user_id")
    List<UserAnswerVO> getUserAnswerInfo();

    /**
     * 获取用户正确数量
     * @param userId
     * @return
     */
    @Select("select count(user_id) from user_answers where user_id = #{userId} and is_correct = 1")
    Integer getCorrectCount(Integer userId);





    /**
     * 获取用户答题统计信息
     *
     * @param userId 用户ID
     * @return 用户答题统计信息
     */
    @Select("SELECT " +
            "COUNT(*) AS totalAnswers, " +
            "SUM(CASE WHEN is_correct = 1 THEN 1 ELSE 0 END) AS correctAnswers, " +
            "ROUND(SUM(CASE WHEN is_correct = 1 THEN 1 ELSE 0 END) * 100.0 / COUNT(*), 2) AS correctRate " +
            "FROM user_answers " +
            "WHERE user_id = #{userId}")
    AnswerStats getUserAnswerStats(@Param("userId") Long userId);

    /**
     * 获取用户专业答题统计信息
     *
     * @param userId 用户ID
     * @return 用户专业答题统计信息
     */
    @Select("SELECT " +
            "m.major_name AS majorName, " +
            "COUNT(*) AS questionCount, " +
            "ROUND(SUM(CASE WHEN ua.is_correct = 1 THEN 1 ELSE 0 END) * 100.0 / COUNT(*), 2) AS correctRate " +
            "FROM user_answers ua " +
            "JOIN questions q ON ua.question_id = q.question_id " +
            "JOIN majors m ON q.major_id = m.major_id " +
            "WHERE ua.user_id = #{userId} " +
            "GROUP BY m.major_id")
    List<MajorStatDTO> getUserMajorStats(@Param("userId") Long userId);

    /**
     * 获取用户答题信息
     * @param userAnswer
     * @return 用户答题信息
     */
    @Select("select * from user_answers where user_id = #{userId} and question_id = #{questionId}")
    UserAnswer getUserAnswer(UserAnswer userAnswer);
}
